// 数据库
const db = require('../db/index');
// 加密插件包
const bcrypt = require('bcryptjs');
// token包
const jwt = require('jsonwebtoken');
// 全局配置
const config = require('../config');

// 登录接口
exports.login = (req, res) => {
	const userinfo = req.body;
	const sql = 'select * from user where phone=?';
	db.query(sql, userinfo.phone, (err, results) => {
		if (err) return res.cc(err);
		if (results.length != 1) return res.cc('没有该用户，请重新确认手机号');
		if (results[0].state === 2) return res.cc('你已离职，无法继续登录');
		// 判断密码是否正确
		if (bcrypt.compareSync(userinfo.password, results[0].password)) {
			// 生成 token 字符串
			const user = {
				...results[0],
				password: '',
				phone: ''
			};
			const tokenStr = jwt.sign(user, config.jwtSecretKey, { expiresIn: config.expiresIn })
			const data = results[0]
			const id_authority = data.id_authority
			// 查询权限
			const sql = 'select * from authority where authority_id=?'
			db.query(sql, id_authority, (err, results) => {
				if(err) return res.cc(err)
				// 查询徽标
				const sql = 'select * from reddot where user_id=?'
				db.query(sql, data.id, (err, reddot) => {
					if(err) return res.cc(err)
					res.send({
						status: 0,
						message: '登录成功！',
						token: 'Bearer ' + tokenStr,
						data: {
							user_id: data.id,
							department_id: data.id_department1,
							nick_name: data.nick_name,
							authority_info: results[0].a_info,
							reddot
						}
					})
				})
			})
		} else {
			return res.cc('密码错误，请重新输入');
		}
	})
}